import axios from 'axios'
import store from '@/store/index';
import { apiUrl } from './globle'
import { Message } from 'element-ui'
import Qs from 'qs'
import { getToken } from "@/http/api"
if (process.env.NODE_ENV == 'development') {
  axios.defaults.baseURL = apiUrl;
} else if (process.env.NODE_ENV == 'production') {
  axios.defaults.baseURL = '';
}
// 响应时间
axios.defaults.timeout = 10000
// post请求头的设置			
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

// 请求拦截器
// 验证token是否失效 isRefreshing防止重复提交导致页面卡死
let isRefreshing = true;
function checkStatus() {
  if (isRefreshing) {
    refreshTokenRequst()
    isRefreshing = false;
  }
}
// 重新请求token
function refreshTokenRequst() {
  const query = Qs.stringify({ grant_type: "password" });
  getToken(query)
    .then(res => {
      const expires = res['.expires'];
      localStorage.setItem("token", res.access_token);
      localStorage.setItem("expires", expires);
    })
    .catch(err => {
      console.log(err);
    });
}
// 请求拦截器
axios.interceptors.request.use(
  config => {
    const expires = localStorage.getItem('expires')
    const nowTime = new Date().getTime();
    const endTime = new Date(expires).getTime();
    if (nowTime >= endTime) {
      if (localStorage.getItem("username")) {
        store.commit('setUsername', '')
        localStorage.removeItem('username')
        Message.error('您的登录已超时，请重新登录...')
      } else {
        checkStatus()
      }
    }
    const token = localStorage.getItem('token')
    config.headers.Authorization = "bearer " + token;
    return config;
  },
  error => {
    return Promise.error(error);
  })
// 响应拦截器
axios.interceptors.response.use(
  res => {
    if (res.status === 200) {
      return Promise.resolve(res);
    } else {
      return Promise.reject(res);
    }
  },
  error => {
    if (error.response.status) {
      switch (error.response.status) {
        case 401:
          router.replace({
            path: '/login',
            query: {
              redirect: router.currentRoute.fullPath
            }
          });
          break;
        case 403:
          Toast({
            message: '登录过期，请重新登录',
            duration: 1000,
            forbidClick: true
          });
          // 清除token
          localStorage.removeItem('token');
          store.commit('loginSuccess', null);
          // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面 
          setTimeout(() => {
            router.replace({
              path: '/login',
              query: {
                redirect: router.currentRoute.fullPath
              }
            });
          }, 1000);
          break;

        // 404请求不存在
        case 404:
          Toast({
            message: '网络请求不存在',
            duration: 1500,
            forbidClick: true
          });
          break;
        default:
          Toast({
            message: error.response.data.message,
            duration: 1500,
            forbidClick: true
          });
      }
      return Promise.reject(error.response);
    }
  });

export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(res => {
      resolve(res.data);
    }).catch(err => {
      reject(err.data)
    })
  });
}

export function post(url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data)
      })
  });
}


